<!-- 竞赛演练生成模板 / 修改模板 / 导入模板-->
<template>
    <Modal
        v-model="modal.show"
        :title="modal.title"
        :loading="modal.loading"
        :mask-closable="false"
        @on-ok="saveTemplate"
        @on-cancel="closeModal"
        :width="modal.width">
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="60">
        <FormItem label="名称" prop="name">
            <Input v-model.trim="formValidate.name" placeholder='请输入不能包含下列任意英文字符 \ / : * ? " < > |，名称长度为1-50个字符'
                :maxlength="50"></Input>
        </FormItem>
        <FormItem label="可见性" prop="visibility">
            <RadioGroup v-model="formValidate.visibility">
                <Radio label='share'>共享</Radio>
                <Radio label='private'>私有</Radio>
            </RadioGroup>
        </FormItem>
        <FormItem label="文件" prop="file" v-if="type === 'import'">
            <Upload ref="upload"
                        :action="upload.uploadAction"
                        :show-upload-list="false"
                        :format="upload.format"
                        :on-format-error="handleFormatError"
                        :before-upload="handleBeforeUpload"
                        :headers="upload.uploadHeader"
                        style="display:inline-block">
                <Button ghost type="primary" :disabled="upload.uploadList.length > 0">
                    <Icon type="ios-cloud-upload-outline"></Icon>
                    <span>选择模板文件</span>
                </Button>
            </Upload>
            <Tooltip content="请选择json格式文件导入"><Icon type="ios-alert" style="color:#f90" size="16"></Icon></Tooltip>
    
            <p v-if="showFileName">{{formValidate.file}}</p>
        </FormItem>
        <FormItem label="描述" prop="description">
            <Input v-model.trim="formValidate.description" type="textarea" :maxlength="200"
                :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入描述"></Input>
        </FormItem>
    </Form>
</Modal>
</template>
<script>
    import {sceneSaveAsTemplate,updateSceneTemplate,importSceneTemplate} from '@/api/drill_compete.js'
    import { validateName ,validateName128,validateNameCustom} from '@/libs/reg'
    export default {
        name:'EditModal',
        props:{
            value: { //显示、隐藏
                type: Boolean,
                default: false
            },
            type:{ //操作类型
                type:String,
                default:'add',
                validate:(val) => { //生成模板、更新、导入
                    return ['add','update','import'].includes(val)
                }
            },
            sceneId:{
               type:String,
               required: this.type === 'add' ? true : false
            },
            data:''
        },
        data(){
            const validateFile = (rule,value,callback) => {
                if(!value){
                    callback('请选择文件');
                }else if(value.split('.').pop() !== 'json'){
                    callback('请选择文件');
                }
                callback()
            }
            const validateName1 = (rule, value, callback) => {
                //验证警戒值
                if (value) {
                    validateNameCustom(rule, value, callback, 50)
                } else {
                    callback();
                }
            }
            return {
                modal:{
                    show:this.value,
                    title:'生成模板',
                    loading:true,
                    width:600
                },
                formValidate: {
                    description: '',
                    name: '',
                    visibility:'share',
                    file:''
                },
                ruleValidate: {
                    name: [
                        {
                            required: true,
                            max: 50,
                            message: '模板名称长度为1-50个字符',
                            trigger: 'change'
                        },
                        {
                            validator: validateName1,
                            trigger: 'change'
                        }
                    ],
                    file:[{required:true,type:'string',validator:validateFile}],
                    visibility:[{required:true,type:'string',message:''}],
                    description: [{ max: 200, message: '描述长度不能超过200个字符', trigger: 'change' }]
                },
                upload:{
                    uploadAction:'/api/compete/sceneTemplate/importSceneTemplate',
                    uploadHeader:{
                        Authorization:localStorage.token,
                        Accept:'*/*'
                    },
                    format:['json'],
                    uploadList:[]
                },
                showFileName:false
            }
        },
        watch: {
            'modal.show':function(val){
                if (!val) {
                    this.$emit('input', false);
                    this.$emit('close');
                }
            },
            value(val) {
                val ? this.showModal() : this.closeModal();
            }
        },
        mounted(){
            this._formValidate = {...this.formValidate};
        },
        methods:{
            saveTemplate(){
                this.$refs.formValidate.validate((valid) => {
                    if(valid){
                        if(this.type === 'update'){
                            //修改模板
                            updateSceneTemplate(this.formValidate.id,this.formValidate).then(({code,data,message}) => {
                                if(code == 1){
                                    this.$Message.info(message);
                                    this.closeModal();
                                    this.$emit('ok')
                                }else{
                                    this.$Message.error(message);
                                }
                            }).catch(e => {
                                this.$Message.error('修改失败');
                            }).finally(() => {
                                this.cancelLoading();
                            })
                        }else if(this.type === 'import'){
                            //导入模板
                            let formData = new window.FormData()
                            formData.append('file',this.file);
                            importSceneTemplate(formData,this.formValidate).then(({code,data,message}) => {
                                if(code == 1){
                                    this.$Message.info('导入成功');
                                    this.closeModal();
                                    this.$emit('ok')
                                }else{
                                    this.$Message.error(message);
                                }
                            }).finally(() => {
                                this.cancelLoading();
                            })
                        }else{
                            // 竞赛页面生成模板
                            sceneSaveAsTemplate(this.sceneId,this.formValidate).then(({code,data,message}) => {
                                if(code == 1){
                                    this.$Message.info('生成模板成功');
                                    this.closeModal();
                                }else{
                                    this.$Message.error(message);
                                }
                            }).catch(e => {
                                this.$Message.error('生成模板失败');
                            }).finally(() => {
                                this.cancelLoading();
                            })
                        }
                    }else{
                        this.cancelLoading();
                    }
                }).catch(error => {
                    this.cancelLoading();
                })
            },
            initData(){
                this.formValidate = {...this._formValidate}
                this.file = '';
            },
            resetField(){
                this.initData();
                this.file = '';
                this.$refs.formValidate.resetFields();
            },
            showModal(){
                this.modal.show = true;
                if(this.type == 'update'){
                    this.modal.title = '修改模板';
                    this.formValidate = {...this.data};
                }else if(this.type == 'import'){
                    this.modal.title = '导入模板';
                }else{
                    this.modal.title = '生成场景模板';
                }
            },
            closeModal(){
                this.modal.show = false;
                this.resetField();
            },
            cancelLoading() {
                this.modal.loading = false;
                setTimeout(() => {
                    this.modal.loading = true;
                });
            },
			handleBeforeUpload(file){
                // const fileSize = file.size / 1024 / 1024 > this.$store.state.common.fileMax;
                // if(fileSize){
                // this.$Message.error({
                //     content: `文件大小不能大于${this.$store.state.common.fileMax}M`,
                //     duration: 2
                // });
                // return false;
                // }
				this.upload.uploadList = this.$refs.upload.fileList;
                this.formValidate.file = file.name;
                this.showFileName = false;
                this.$refs['formValidate'].validateField('file',(error) => {
                    if(!error){
                        this.file = file; //导入的时候用
                        this.showFileName = true;
                    }else{
                        this.formValidate.file =''
                        this.showFileName = false;
                        this.$Message.warning(error);
                    }
                });
				return false;
			},
            handleFormatError(){
                
            },
        }
    }
</script>
<style scoped>
</style>